<template>
    <div>
      <div class="input-section">
        <div class="right">
          <el-input
            v-model="searchClubId"
            placeholder="请输入社团id"
            style="
              width: 400px;
              height: 40px;
              margin-bottom: 20px;
              margin-top: 20px;
              padding: 0px 10px;
            "
            :prefix-icon="Search"
            clearable
          />
          <el-input
            v-model="searchClubName"
            placeholder="请输入社团名称"
            style="
              width: 400px;
              height: 40px;
              margin-bottom: 20px;
              margin-top: 20px;
              padding: 0px 10px;
            "
            clearable
          />

          <el-button type="primary" @click="searchClub">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <!-- 新增：Excel 按钮 -->
          <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
          <input type="file" @change="importFromExcel" accept=".xlsx, .xls" style="display: none;" ref="fileInputRef" />
          <!-- <el-button @click="$refs.fileInputRef.click()" type="warning">导入 Excel</el-button> -->
          <!-- <el-button @click="handleFileInputClick" type="warning">导入 Excel</el-button> -->
        </div>
      </div>
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        row-key="id"
      >
       <el-table-column label="" width="50"> 
        <template #default="{ row }">
            <el-icon v-if="row.status === 0" color="green">
            <Sunrise />
            </el-icon>
            <el-icon v-else-if="row.status === 1" color="red">
            <Sunny />
            </el-icon>
            <el-icon v-else-if="row.status === 2" color="gray">
            <Sunset />
            </el-icon>
        </template>
        </el-table-column> 
        <el-table-column prop="clubVO.id" label="社团id" width="150" />
        <el-table-column prop="clubVO.clubName" label="社团名称" width="180" />
        <el-table-column prop="clubVO.userVO.userName" label="社长" width="180" />
        <el-table-column prop="clubVO.introduction" label="社团简介" width="250" />
        <el-table-column
          prop=" status"
          label="身份"
          width="180"
          :filters="statusFilters"
          :filter-method="filterType"
          filter-placement="bottom-end"
        > 
          <template #default="scope">
            <el-tag :type="getIdentityTagType(scope.row.identity)">
            {{ getIdentityText(scope.row.identity) }}
            </el-tag>
        </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row, $index }">
            <el-button size="small" @click="handleView(row)">查看社团</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-section">
        <span class="record-count"> 共查询到 {{ total }} 条记录</span>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          v-model:page-size="pageSize"
          v-model:current-page="currentPage"
          :page-sizes="[8, 16, 32, 64]"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 查看活动详情的对话框 -->
      <el-dialog v-model="viewDialogVisible" title="社团详情" width="50%">
        <el-descriptions border :column="2">
          <el-descriptions-item label="社团ID">{{
            currentViewClub.clubVO.id
          }}</el-descriptions-item>
          <el-descriptions-item label="社团名称">{{
            currentViewClub.clubVO.clubName
          }}</el-descriptions-item>
          <el-descriptions-item label="社长">{{
            currentViewClub.clubVO.userVO.userName
          }}</el-descriptions-item>
          <el-descriptions-item label="社团标签">{{
            currentViewClub.clubVO.tags
          }}</el-descriptions-item>
          <el-descriptions-item label="社团公告" :span="2">
            <div style="white-space: pre-line">
              {{ currentViewClub.clubVO.announcement }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="社团简介" :span="2">
            <div style="white-space: pre-line">
              {{ currentViewClub.clubVO.introduction }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="社团人数">{{
            currentViewClub.clubVO.memberCount
          }}</el-descriptions-item>
          <el-descriptions-item label="身份">
            <el-tag :type="getIdentityTagType(currentViewClub.identity)">
              {{ getIdentityText(currentViewClub.identity) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div> 
  </template>

<script setup lang="ts">
import { ref , computed} from "vue";
import { ElMessage } from "element-plus";
import { Search } from '@element-plus/icons-vue';
import { Sunrise, Sunny, Sunset } from '@element-plus/icons-vue';
import { useUserStore } from '../../../stores/user'
import { ClubControllerService } from "../../../../generated/services/ClubControllerService";
import { onMounted } from "vue";
import type { ClubMemberQueryRequest, ClubVO, ClubMembershipVO } from "../../../../generated";


const store = useUserStore();  // 使用 Pinia 的用户存储
const nowUserId = store.id;
const tableData = ref<ClubMembershipVO[]>([]);  // 表格数据
const total = computed(() => tableData.value?.length||0);     // 总条数
const pageSize = ref(8);
const currentPage = ref(1);


// 显示用户的社团列表
// 使用 ActivityControllerService 获取用户活动列表
const loadClub = async () => {
  try {
    const response = await ClubControllerService.listClubVoOfUserByPage({
      userId: nowUserId,               // 
      current: currentPage.value,     // 分页
      pageSize: pageSize.value,
    } as ClubMemberQueryRequest);

    
    if (response.code === 0 && response.data) {
      tableData.value = response.data.records as ClubMembershipVO[];
      
    //   total.value = Number(response.data.total); // 确保 total 是数字类型
      console.log("加载社团数据成功：", response);

      // 打印每个活动的 status
    //   tableData.value.forEach((activity) => {
    //     console.log(`活动ID: ${activity.id}, 状态: ${activity.status}`);
    //   });
    } else {
      ElMessage.error("加载活动失败：" + response.message);
    }
  } catch (err) {
    console.error("请求出错：", err);
    ElMessage.error("网络请求异常！");
  }
};

onMounted(() => {
  loadClub();  // 页面加载时自动查询
});


// 搜索相关
const searchClubId = ref("");
const searchClubName = ref("");

// 搜索活动
const searchActivityById = async () => {
  try {
    // 将输入字符串转成数字，如果转不了就是 NaN
    const clubIdNumber = Number(searchClubId.value);

    // 非法 ID 检查（NaN 或 <= 0）
    if (!searchClubId.value || isNaN(clubIdNumber) || clubIdNumber <= 0) {
      ElMessage.warning("请输入有效的社团 ID（数字）");
      return;
    }

    console.log("搜索社团 ID：", clubIdNumber);

    console.log("请求参数：", {
        userId: nowUserId,
        clubId: clubIdNumber,
        current: currentPage.value,
        pageSize: pageSize.value,
    });

    const response = await ClubControllerService.listClubVoOfUserByPage({
      userId: nowUserId,
      clubId: clubIdNumber, // 将输入的活动Id转换为数字
      current: currentPage.value,
      pageSize: pageSize.value,
    });

    if (response.code === 0 && response.data) {
    //   tableData.value = response.data.records;
      tableData.value = response.data.records as ClubVO[];
    //   total.value = Number(response.data.current);
      ElMessage.success("搜索成功！");
    } else {
      ElMessage.warning("没有搜索到相关社团！");
    }
  } catch (err) {
    console.error("搜索失败：", err);
    ElMessage.error("搜索请求失败！");
  }
};

const searchClub = () => {
  const clubIdNumber = Number(searchClubId.value);

  const isIdValid =
  searchClubId.value &&
    !isNaN(clubIdNumber) &&
    clubIdNumber > 0;

  const hasClubName = searchClubName.value.trim().length > 0;

  if (!isIdValid && !hasClubName) {
    ElMessage.warning("请输入有效的活动 ID 或社团名进行搜索");
    return;
  }

  // 前端过滤：按活动 ID
  if (isIdValid) {
    tableData.value = tableData.value.filter((item) => {
    console.log(item)
    console.log(item.clubVO?.id as number === clubIdNumber)
    return item.clubVO?.id === clubIdNumber});
  }

  // 前端过滤：按社团名模糊匹配
  if (hasClubName) {
    const lowerName = searchClubName.value.toLowerCase();
    tableData.value = tableData.value.filter((item) =>
      item.clubVO?.clubName?.toLowerCase().includes(lowerName)
    );
  }

  currentPage.value = 1;
  ElMessage.success("搜索成功！");
};


// 重置搜索
const resetSearch = () => {
    searchClubId.value = "";
    searchClubName.value = "";
    loadClub();
    ElMessage.info("搜索已重置！");
};

const currentViewClub = ref<any>({});
const viewDialogVisible = ref(false);

// 点击查看活动详情
const handleView = (row: any) => {
    console.log("试图打开查看社团对话框");
    currentViewClub.value = row;
    // 从 row.clubVO 中提取社团信息
    // 打开查看详情对话框
  viewDialogVisible.value = true;
  console.log("查看社团对话框状态：", viewDialogVisible.value);
};


// 分页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadClub();
};




//处理状态文本和标签类型
// 状态过滤器
const statusFilters = [
  { text: "社长", value: 0 },
  { text: "进行中", value: 1 },
  { text: "已结束", value: 2 },
];


// 在 <script setup> 中添加如下方法
const getIdentityText = (identity: string) => {
  return identity === 'manager' ? '社长' : '社员';
};

const getIdentityTagType = (identity: string) => {
  return identity === 'manager' ? 'success' : 'info';
};

// 过滤方法

const filterType = (value: any, row: any, column: any) => {
  // 根据列的 `prop` 属性进行过滤
  if (column.property === "status") {
    return row.status === value;
  } else if (column.property === "isDelete") {
    return row.isDelete === value;
  }
  return false;
};



import * as XLSX from 'xlsx';
const fileInputRef = ref<HTMLInputElement | null>(null);
// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    '社团ID': item.id,
    '社团名称': item.clubName || '未知',
    '社长': item.userVO?.userName || '未知',
    '社团简介': item.introduction || '无',
    '身份': getIdentityText(item.userVO?.userRole || '未知'),
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '社团信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};





// 导入 Excel

const handleFileInputClick = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  } else {
    console.error("fileInputRef 未正确绑定");
    ElMessage.error("无法打开文件选择器，请检查代码");
  }
};

import { AdminClubControllerService } from '../../../../generated/services/AdminClubControllerService';
import type { ClubMembershipAddRequest } from '../../../../generated';

const importFromExcel = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;

  if (!files || files.length === 0) {
    ElMessage.warning("请选择一个 Excel 文件");
    return;
  }

  const file = files[0];
  const reader = new FileReader();

  interface ExcelRow {
  社团ID: string | number;
  用户ID: number; // 假设你的后端支持 userName 添加用户，否则需改为 userId
  社长: string;
  身份: string;
  }

  reader.onload = async (e) => {
    const data = new Uint8Array(e.target?.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: "array" });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];

    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    console.log("Excel 导入的数据：", jsonData);

    // 遍历每行数据，并调用接口写入后端
    let successCount = 0;
    let failCount = 0;

    for (const row of jsonData as ExcelRow[]) {
      const request: ClubMembershipAddRequest = {
        clubId: Number(row['社团ID']),
        userId: row['用户ID'], // 假设你的后端支持 userName 添加用户，否则需改为 userId
        identity: row['身份'] === '社长' ? 'manager' : 'member',
      };

      try {
        const response = await AdminClubControllerService.addMemberToClub(request);
        if (response.code === 0 && response.data === true) {
          successCount++;
        } else {
          console.warn("添加失败：", response.message);
          failCount++;
        }
      } catch (error) {
        console.error("请求异常：", error);
        failCount++;
      }
    }

    // 导入完成反馈
    ElMessage.success(`导入完成：成功 ${successCount} 条，失败 ${failCount} 条`);

    // 重新加载社团数据
    await loadClub();
  };

  reader.readAsArrayBuffer(file);
};



</script>


<style scoped lang="scss">
.input-section {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;

  .right {
    display: flex;
    align-items: center;

    el-input {
      margin-right: 10px;
    }

    el-button {
      margin-left: 10px;
    }
  }
}

.el-table {
  margin-top: 20px;

  .el-table-column {
    text-align: center;
  }
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  .record-count {
    font-size: 14px;
    color: #666;
  }

  el-pagination {
    margin-left: auto;
  }
}

.el-dialog {
  .el-descriptions {
    margin-top: 10px;

    .el-descriptions-item {
      font-size: 14px;
      color: #333;

      div {
        white-space: pre-line;
      }
    }

    .el-tag {
      font-size: 12px;
    }
  }
}

.el-button {
  &.small {
    font-size: 12px;
    padding: 5px 10px;
  }
}
.input-section input[type="file"] {
  display: none;
}
</style>